package com.example.watermark;

import com.example.bean.WaterSenSorFunction;
import com.example.bean.WaterSensor;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.datastream.WindowedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * Created with IntelliJ IDEA.
 * ClassName: WindowRdeuceDemo
 * Package: com.example.window
 * Description:
 * User: fzykd
 *
 * @Author: LQH
 * Date: 2023-07-19
 * Time: 17:41
 */

public class WatermarkOutOfOrderNessDemo {

    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env =
                StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(1);

        SingleOutputStreamOperator<WaterSensor> data = env.socketTextStream("hadoop102", 7777)
                .map(new WaterSenSorFunction());

        //指定watermark策略
        WatermarkStrategy<WaterSensor> watermarkStrategy = WatermarkStrategy
                //前面要指定数据类型泛型
                //Duration持续时间 等待3秒
                .<WaterSensor>forBoundedOutOfOrderness(Duration.ofSeconds(3)) //乱序的 有界限的 说明可以等 等多久
                //forMonotonousTimestamps() //升序的 单调递增的
                //指定时间戳分配器 从数据中提取事件时间
                .withTimestampAssigner(new SerializableTimestampAssigner<WaterSensor>() {
                    //参数要传一个可序列化的事件提取器
                    @Override
                    //重写方法是提取事件戳 单位 毫秒
                    public long extractTimestamp(WaterSensor element, long recordTimestamp) {
                        System.out.println("数据=" + element + "recordTs=" + recordTimestamp);
                        //返回的时间戳是毫秒
                        return element.getTs() * 1000L;
                    }
                });

        SingleOutputStreamOperator<WaterSensor> waterSensorSingleOutputStreamOperator =
                data.assignTimestampsAndWatermarks(watermarkStrategy);


        KeyedStream<WaterSensor, String> sensorKS = waterSensorSingleOutputStreamOperator.keyBy(value -> value.getId());


        //并且要规定窗口 之前是处理时间的窗口
        //但是WaterMake是基于事件事件的窗口
        WindowedStream<WaterSensor, String, TimeWindow> sensorWS =
                //使用事件时间语义的 窗口
                sensorKS.window(TumblingEventTimeWindows.of(Time.seconds(10)));

        //全窗口 来一条数据 存起来 到窗口触发在全部统一计算 提供了上下文信息
        SingleOutputStreamOperator<String> process = sensorWS.process(new ProcessWindowFunction<WaterSensor, String, String, TimeWindow>() {
            /**
             * 全窗口计算逻辑 窗口触发时候才会被调用一次
             * @param s 分组的key
             * @param context 上下文
             * @param elements 存的数据
             * @param out 采集器
             * @throws Exception
             */
            @Override
            public void process(String s, Context context, Iterable<WaterSensor> elements, Collector<String> out) throws Exception {
                //上下文 可以获取窗口的一些信息 启停时间
                long start = context.window().getStart();
                long end = context.window().getEnd();
                //格式准换
                String sW = DateFormatUtils.format(start, "yyy-MM-dd HH:mm:ss.SSS");
                String eW = DateFormatUtils.format(end, "yyy-MM-dd HH:mm:ss.SSS");

                //答应集合数量
                long l = elements.spliterator().estimateSize();

                out.collect("key=" + s + "的窗口[" + sW + "," + eW + "] 包含" + l + "条数据 ===> " + elements.toString());


            }
        });
        process.print();


        env.execute();
    }

}

/**内置Watermark的生成器
 * 1.都是周期性的生成 默认200ms
 * 2.升序流： watermark = 当前最大的事件事件 - 1ms 底层还是调用了乱序 只是将延迟事件设置位0
 * 3.乱序流： watermark = 当前最大的事件事件 - 延迟事件 - 1ms
 */
